package com.ma5d.driver.customer.service.impl;

import com.ma5d.driver.common.constant.RedisConstant;
import com.ma5d.driver.common.exception.DriverException;
import com.ma5d.driver.common.result.Result;
import com.ma5d.driver.common.result.ResultCodeEnum;
import com.ma5d.driver.customer.client.CustomerInfoFeignClient;
import com.ma5d.driver.customer.service.CustomerService;
import com.ma5d.driver.model.form.UpdateWxPhoneForm;
import com.ma5d.driver.model.vo.customer.CustomerLoginVo;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class CustomerServiceImpl implements CustomerService {
    @Resource
    private CustomerInfoFeignClient customerInfoFeignClient;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public String login(String code) {
        Result<Long> longResult = customerInfoFeignClient.login(code);
        Integer codeResult = longResult.getCode();
        if(codeResult != 200){
            throw new DriverException(ResultCodeEnum.DATA_ERROR);
        }
        Long customerId = longResult.getData();
        if(customerId == null){
            throw new DriverException(ResultCodeEnum.DATA_ERROR);
        }
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + token,
                customerId.toString(),
                RedisConstant.USER_LOGIN_KEY_TIMEOUT,
                TimeUnit.SECONDS);
        return token;
    }

    @Override
    public CustomerLoginVo getCustomerLoginVo(String token) {
        String customerId = redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        if(!StringUtils.hasText(customerId)){
            throw new DriverException(ResultCodeEnum.DATA_ERROR);
        }
        Result<CustomerLoginVo> customerLoginVoResult = customerInfoFeignClient.getCustomerLoginInfo(Long.parseLong(customerId));
        if (customerLoginVoResult.getCode() != 200) {
            throw new DriverException(ResultCodeEnum.DATA_ERROR);
        }
        return customerLoginVoResult.getData();
    }

    @Override
    public CustomerLoginVo getCustomerVo(Long customerId) {
        Result<CustomerLoginVo> customerLoginVoResult = customerInfoFeignClient.getCustomerLoginInfo(customerId);
        if (customerLoginVoResult.getCode() != 200) {
            throw new DriverException(ResultCodeEnum.DATA_ERROR);
        }
        return customerLoginVoResult.getData();
    }

    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        Result<Boolean> booleanResult = customerInfoFeignClient.updateWxPhoneNumber(updateWxPhoneForm);
        return booleanResult.getData();
    }
}
